package net.aaa.hotel.controller;

import com.alibaba.fastjson.JSON;
import net.aaa.hotel.dao.DeptDao;
import net.aaa.hotel.dao.impl.DeptDaoImpl;
import net.aaa.hotel.entity.Dept;
import net.aaa.hotel.util.TransBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/dept")
public class DeptController extends HttpServlet {
    private DeptDao dao = new DeptDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        String method = req.getParameter("method");
        if (method != null) {
            switch (method) {
                case "add":
                    addDept(req, resp);
                    break;
                case "del":
                    delDept(req, resp);
                    break;
            }
        } else {
            List<Map> maps = dao.findAll();
            Map m = new HashMap();
            m.put("code", 0);
            m.put("msg", "");
            m.put("count", maps.size());
            m.put("data", maps);
            String string = JSON.toJSONString(m);
            PrintWriter out = resp.getWriter();
            out.write(string);
        }
    }

    private void delDept(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String gid = req.getParameter("gid");
        int i = dao.delDept(gid);
        PrintWriter out = resp.getWriter();
        out.write(i);
        out.flush();
        out.close();
    }

    private void addDept(HttpServletRequest req, HttpServletResponse resp) {
        Map<String, String[]> map = req.getParameterMap();
        Dept dept = new Dept();
        TransBean.populate(dept, map);
        int i = dao.addDept(dept);
    }
}
